#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    tcpServer = new QTcpServer(this);

    this->setWindowTitle("TCP服务端");
    //新的连接
    connect(tcpServer,SIGNAL(newConnection()),this,SLOT(mNewConnetion()));
}

Widget::~Widget()
{
    delete ui;
}

void Widget::mNewConnetion()
{
    //与客户端链接
    QTcpSocket *tmpTcpSocket=tcpServer->nextPendingConnection();

    //打印客户端链接的IP信息

    ui->textBrowser->append("客户端ip地址："+ tmpTcpSocket->peerAddress().toString());
    ui->textBrowser->append("客户端端口："+ QString::number(tmpTcpSocket->peerPort()));

    //连接信号和槽
    connect(tmpTcpSocket,SIGNAL(readyRead()),this,SLOT(receiveMessages()));

    connect(tmpTcpSocket,SIGNAL(stateChanged(QAbstractSocket::SocketState)),
            this,SLOT(mStateChanged(QAbstractSocket::SocketState)));

}

void Widget::receiveMessages()
{
    QTcpSocket *tmpTcpSocket = (QTcpSocket *)sender();
    //打印接受的消息
    ui->textBrowser->append("来自客户端的消息："+tmpTcpSocket->readAll());
}

void Widget::mStateChanged(QAbstractSocket::SocketState state)
{
    QTcpSocket *tmpTcpSocket = (QTcpSocket *)sender();

    switch(state){

    case QAbstractSocket::UnconnectedState:
        ui->textBrowser->append("客户端断开连接");

        tmpTcpSocket->deleteLater();

        //delete tmpTcpSocket;
        break;
    case QAbstractSocket::ConnectedState:
        ui->textBrowser->append("客户端已连接");
        break;
    default:
        break;
    }
}



void Widget::on_sendMessages_clicked()
{
    QList <QTcpSocket *> socketList = tcpServer->findChildren<QTcpSocket *>();

    if(socketList.count()==0)
    {
        ui->textBrowser->append("当前无客户端连接，请先连接客户端");
        return;
    }
    foreach (QTcpSocket *tmeTcpSocket, socketList) {
        //服务端向每个客户端发消息
        tmeTcpSocket->write(ui->lineEdit->text().toUtf8());

    }
}

void Widget::on_startMonitor_clicked()
{
    //监听ip端口

    QList<QHostAddress> ipAddresses;
    QList<QNetworkInterface> interfaces = QNetworkInterface::allInterfaces();

    foreach (QNetworkInterface interface, interfaces) {
        if (interface.flags().testFlag(QNetworkInterface::IsUp) && !interface.flags().testFlag(QNetworkInterface::IsLoopBack)) {
            QList<QNetworkAddressEntry> entryList = interface.addressEntries();
            foreach (QNetworkAddressEntry entry, entryList) {
                if (entry.ip().protocol() == QAbstractSocket::IPv4Protocol) {
                    ipAddresses.append(entry.ip());
                    //qDebug() << "IPv4 Address:" << entry.ip().toString();

                    bool ok = false;
                    tcpServer->listen(QHostAddress(entry.ip().toString()),ui->portlineEdit->text().toUShort(&ok));
                    ui->textBrowser->append("TCP服务器打开" + entry.ip().toString() + ":" + ui->portlineEdit->text());
                }
            }
        }
    }
    ui->startMonitor->setEnabled(false);
    ui->stopMonitor->setEnabled(true);
}

void Widget::on_stopMonitor_clicked()
{    

    tcpServer->close();

    // 关闭所有现有的连接
    QList<QTcpSocket*> sockets = tcpServer->findChildren<QTcpSocket *>();
    for (QTcpSocket *socket : sockets) {
        socket->disconnectFromHost(); // 尝试断开连接
        socket->waitForDisconnected(5000); // 等待连接断开，可以设置超时

        // 如果连接在超时后仍然打开，可以选择强制关闭它
        if (socket->state() == QAbstractSocket::ConnectedState) {
            socket->abort();
        }

        // 你可以在这里安全地删除socket，因为QTcpServer不再管理它
        // 但请注意，不要在循环中直接delete socket，因为这可能会导致问题
        // 使用deleteLater()来在事件循环的下一个迭代中删除它
        socket->deleteLater();
    }

    ui->textBrowser->append("服务器关闭");
    ui->startMonitor->setEnabled(true);
    ui->stopMonitor->setEnabled(false);
}
